<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <page-form
      class="paddingBox order-model-formBox flex_wrap_start_start"
      v-model:ref-obj="formInfo.ref"
      :data="formInfo.data"
      :field-list="formInfo.fieldList"
      :rules="formInfo.rules"
      :label-width="formInfo.labelWidth"
    >
      <template v-if="showDept" v-slot:form-useDeptName>
        <el-input
          v-model="formInfo.data.useDeptName"
          type="input"
          :disabled="true"
          class="not-mongolia"
          placeholder="请选择使用部门"
        >
          <template #append>
            <el-icon @click="openDeptList"><MoreFilled /></el-icon>
          </template>
        </el-input>
      </template>
      <template v-slot:form-assetCapitalSourceVOList>
        <el-form
          ref="assetCapitalSourceTableForm"
          :model="formInfo"
          style="width: 100%"
        >
          <page-table
            v-model:data="formInfo.data.assetCapitalSourceVOList"
            :pager="false"
            :check-box="false"
            :tab-index="true"
            :summary="true"
            :summary-field-list="assetCapitalSourceTableInfo.summaryFieldList"
            :field-list="assetCapitalSourceTableInfo.fieldList"
            :handle="assetCapitalSourceTableInfo.handle"
          >
            <template v-slot:col-code="scope">
              <el-form-item>
                <select-model
                  v-model.lazy="scope.row.code"
                  :check-default="false"
                  style="width: 100%"
                  :type-code="`asset_capital_source`"
                  :clearable="true"
                />
              </el-form-item>
            </template>
            <template v-slot:col-amount="scope">
              <el-form-item
                :prop="`data.assetCapitalSourceVOList.${scope.$index}.amount`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: $validate.positiveMoneyZeroAsset,
                          trigger: ['blur', 'change'],
                        },
                      ]
                    : []
                "
              >
                <el-input-number
                  v-model.lazy="scope.row.amount"
                  style="width: 100%"
                  clearable
                  controls-position="right"
                  :precision="
                    $store.state.permission.systemConfig.assets_price_precision
                  "
                  :min="0"
                  :max="999999999999999"
                  @change="changeAmount"
                />
              </el-form-item>
            </template>
          </page-table>
        </el-form>
      </template>
    </page-form>
    <select-dept
      v-if="selectUseDeptInfo.visible"
      v-model:show-dialog="selectUseDeptInfo.visible"
      :query="selectUseDeptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectUseDeptCallback"
    />
  </page-dialog>
</template>

<script setup name="DialogAutoBuildCard">
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  showDept: {
    type: Boolean,
    default: true,
  },
})
const formInfo = ref({
  ref: null,
  data: {
    assetCapitalSourceVOList: [{ code: '1', amount: 0 }],
  },
  fieldList: [
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'slot',
      show: true,
      disabled: false,
    },
    {
      label: '资金来源',
      value: 'assetCapitalSourceVOList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    useDeptName: [
      { required: true, message: '请选择使用部门', target: 'change' },
    ],
  },
  labelWidth: '120px',
})
const selectUseDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
//资金来源表格
const assetCapitalSourceTableInfo = ref({
  summaryFieldList: [
    { value: 'amount', formatter: proxy.$fn.TripartiteMethodAsset },
  ],
  fieldList: [
    {
      label: '资金来源',
      value: 'code',
      type: 'slot',
    },
    {
      label: '金额',
      value: 'amount',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: addSource,
        show: true,
      },
      {
        label: '删除',
        event: removeSource,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderRemoveSource,
      },
    ],
  },
})
const dialogInfo = ref({
  title: '选择资金来源和使用部门',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: false,
      event: save,
      show: true,
    },
  ],
})
const changeAmountFlag = ref(undefined)

const shows = computed({
  get() {
    setFieldShow()
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

setData()
function setData() {
  dialogInfo.value.title = props.showDept
    ? '选择资金来源和使用部门'
    : '选择资金来源'
}
function setFieldShow() {
  formInfo.value.fieldList[0].show = props.showDept
}
function ifRenderRemoveSource() {
  //资金来源列表是否显示删除
  if (formInfo.value.data.assetCapitalSourceVOList.length - 1) {
    return true
  } else {
    return false
  }
}
function openDeptList() {
  selectUseDeptInfo.value.visible = true
}
function changeAmount() {
  changeAmountFlag.value = true
  let primitiveOriginalAmount = 0
  if (
    formInfo.value.data.assetCapitalSourceVOList &&
    formInfo.value.data.assetCapitalSourceVOList.length
  ) {
    formInfo.value.data.assetCapitalSourceVOList.forEach((item) => {
      primitiveOriginalAmount = proxy.$fn.accAdd(
        item.amount || 0,
        primitiveOriginalAmount
      )
    })
  }
  formInfo.value.data['primitiveOriginalAmount'] = primitiveOriginalAmount
}
function addSource() {
  //增加资金来源
  formInfo.value.data.assetCapitalSourceVOList.unshift({
    code: '',
    amount: 0,
  })
  proxy.$nextTick(() => {
    proxy.$refs.assetCapitalSourceTableForm.clearValidate(
      `data.assetCapitalSourceVOList.0.code`
    )
  })
}
function removeSource(row) {
  //删除资金来源
  formInfo.value.data.assetCapitalSourceVOList =
    formInfo.value.data.assetCapitalSourceVOList.filter((item) => item !== row)
  changeAmount()
}
function selectUseDeptCallback(row) {
  if (row) {
    formInfo.value.data['useDeptId'] = row.id
    formInfo.value.data['useDeptName'] = row.name
  } else {
    formInfo.value.data['useDeptId'] = ''
    formInfo.value.data['useDeptName'] = ''
  }
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let item = formInfo.value.data.assetCapitalSourceVOList.filter(
        (item) => item.code && item.amount >= 0
      )
      if (props.showDept) {
        if (item.length === 0) {
          delete formInfo.value.data.assetCapitalSourceVOList
        }
        emits('updateFormInfo', formInfo.value.data)
      } else {
        if (item.length) {
          emits('updateFormInfo', formInfo.value.data)
        } else {
          emits('updateFormInfo')
        }
      }
      handleClose()
    }
  })
}
function handleClose() {
  //关闭摊销弹窗
  formInfo.value.data = {
    assetCapitalSourceVOList: [{ code: '', amount: 0 }],
  }
  shows.value = false
}
</script>
<style lang="less" scoped></style>
